package com.touchy.touchpad;


import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Touchpad extends Activity implements AccelerometerListener {
	int mode = 0;
	TextView maintextview;
	private static Context CONTEXT;
	static Socket clientSocket = null;
	static ObjectOutputStream os = null;
	DataPacket pack = null;
	float maxTouch = 0;
	float maxDisplacement = 0;
	float minDisplacement = 0;
	Button button1;
	Button button2;
	String ip;
	EditText editip;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.title);
        Button button0 = (Button) findViewById(R.id.titleenter);
        button0.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	editip = ((EditText)findViewById(R.id.ipEdit));
            	ip = editip.getText().toString();
                start();
            }
        });
    }
    
    public void start(){
        try {
        	//"128.61.120.131"
			clientSocket = new Socket(ip, 2323);
			os = new ObjectOutputStream(clientSocket.getOutputStream());
			Log.d("touchscreen", "CONNECTIONS ESTABLISHED");
			
			pack = new DataPacket(400, 400, new DataHeader(true, 0, mode));
            try {
				os.writeObject(pack);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			//System.exit(1);
		}
        
        setContentView(R.layout.tpmain);
        
        CONTEXT = this;
        
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        maintextview = (TextView)findViewById(R.id.maintext);
        maintextview.setText("Touch Pad");
        maintextview.setTextColor(Color.YELLOW);
        maintextview.setTextSize(32);
        
        /*
        button1.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("someshit", "KeyPress");
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                	Log.d("someshit", "KeyPress");
                }
                return true;
            }
        });*/
        
        
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pack = new DataPacket(0,0,new DataHeader(false, 16, mode));
                try {
					os.writeObject(pack);
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	pack = new DataPacket(0,0,new DataHeader(false, 4, mode));
                try {
					os.writeObject(pack);
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        });
        
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_accel:
            mode = 1;
            maintextview.setText("Air Mouse");
            return true;
        case R.id.menu_touch:
            mode = 0;
            maintextview.setText("Touch Pad");
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override public boolean onTouchEvent(MotionEvent event) {
    	if(mode == 0 /*&& Math.max(event.getX(), event.getY()) > .1 * maxTouch*/ ){
    		
    		pack = new DataPacket(event.getX(), event.getY(), new DataHeader(true, 0, mode));
            try {
				os.writeObject(pack);
			} catch (IOException e) {
				e.printStackTrace();
			}
			/*
			if(Math.max(event.getX(), event.getY()) > maxTouch)
				maxTouch = Math.max(event.getX(), event.getY());
    		*/
    		Log.d("touchscreen", "X: "+event.getX() + " Y: " + event.getY());

    		return true;
    	}else{
    		return true;
    	}
    }
    
    public void onDisplacementChanged(float x, float y, float z, float timeDiff) {
    	if(mode == 1 && (Math.max(x, z) > .1 * maxDisplacement || Math.min(x, z) < .1 * minDisplacement) ){
        /*((TextView) findViewById(R.id.x)).setText(String.valueOf(x));
        ((TextView) findViewById(R.id.y)).setText(String.valueOf(y));
        ((TextView) findViewById(R.id.z)).setText(String.valueOf(z));
        */
    		
    		pack = new DataPacket(x, z, new DataHeader(true, 0, mode));
            try {
				os.writeObject(pack);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			if(Math.max(x, z) > maxDisplacement){
				maxDisplacement = Math.max(x, z);
			}
			if(Math.min(x, z) > minDisplacement){
				minDisplacement = Math.min(x, z);
			}
			
			Log.d("Displacement ", " x: "+ x + " y: " + y + " z: " + z + " timediff: " + timeDiff);
    	}
    }
    
    protected void onResume() {
        super.onResume();
        if (AccelerometerManager.isSupported()) {
            AccelerometerManager.startListening(this);
        }
    }
 
    protected void onDestroy() {
        super.onDestroy();
        if (AccelerometerManager.isListening()) {
            AccelerometerManager.stopListening();
        }
    }
    
    public static Context getContext() {
        return CONTEXT;
    }
}